package org.demo.honor.representation.mq;

import com.rabbitmq.client.Channel;
import java.util.List;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.demo.honor.integration.dto.PaymentMessageDTO;
import org.demo.honor.service.OrderService;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

@Component
@AllArgsConstructor
public class PaymentListener {

    private final OrderService orderService;

    @RabbitListener
    @SneakyThrows
    public void handlePaymentMessages(List<PaymentMessageDTO> messages, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        try {
            for (PaymentMessageDTO message : messages) {
                handlePaymentMessage(message);
            }
            channel.basicAck(messages.size(), true);
        } catch (Exception e) {
            channel.basicNack(messages.size(), false, false);
        }
    }

    public void handlePaymentMessage(PaymentMessageDTO message) {

        orderService.orderPay(message);

    }
}
